package com.jinke.api.modules.app.controller;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jinke.api.common.api.CommonPage;
import com.jinke.api.common.api.CommonResult;
import com.jinke.api.modules.app.controller.param.MaterialRechargeParam;
import com.jinke.api.modules.app.enums.CoinType;
import com.jinke.api.modules.app.enums.PaymentType;
import com.jinke.api.modules.app.enums.UserRechargeStatus;
import com.jinke.api.modules.app.model.UserRecharge;
import com.jinke.api.modules.app.request.UserRechargeRequest;
import com.jinke.api.modules.app.request.UserRechargeSubmitRequest;
import com.jinke.api.modules.app.response.UserRechargeExport;
import com.jinke.api.modules.app.response.UserRechargeListVO;
import com.jinke.api.modules.app.service.UserRechargeService;
import com.jinke.api.modules.ums.constant.ConfigConstant;
import com.jinke.api.modules.ums.model.SystemConfig;
import com.jinke.api.modules.ums.model.UmsAdmin;
import com.jinke.api.modules.ums.service.SystemConfigService;
import com.jinke.api.modules.ums.vo.SimpleUser;
import com.jinke.api.security.util.AdminUserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.dreamlu.mica.core.utils.BeanUtil;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

import static com.jinke.api.modules.third.dqpost.util.DqpostlUtil.NUM_PLACES;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author macro
 * @since 2024-01-13
 */
@RestController
@RequestMapping("/app/user/recharge")
@Api(value = "用户充值", tags = "用户充值")
public class UserRechargeController {
    @Resource
    private StaticController staticController;
    @Resource
    private UserRechargeService userRechargeService;

    @Resource
    private SystemConfigService systemConfigService;

    @ApiOperation(value = "提交充值")
    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<?> submit(@Validated @RequestBody UserRechargeSubmitRequest request) {
        UserRecharge userRecharge = new UserRecharge();
        BeanUtil.copy(request, userRecharge);

        // 设置状态和名称
        UmsAdmin userInfo = AdminUserUtil.getUserInfo();
        userRecharge.setStatus(UserRechargeStatus.PENDING);
        userRecharge.setUserId(userInfo.getId());
        userRecharge.setSellerId(userInfo.getSellerId());

        SystemConfig systemConfig = systemConfigService.getByKey(ConfigConstant.USD_RATE);
        BigDecimal exchangeRate = BigDecimal.ONE;
        if (systemConfig != null) {
            exchangeRate = systemConfig.toBigDecimal();
        }

        CoinType coinType = userRecharge.getCoinType();
        if (CoinType.USDT.equals(coinType)) {
            userRecharge.setUsdAmount(userRecharge.getAmount());
        } else {
            userRecharge.setUsdAmount(userRecharge.getAmount().divide(exchangeRate,NUM_PLACES,  RoundingMode.DOWN));
        }
        userRecharge.setUsdRate(exchangeRate);
        userRechargeService.save(userRecharge);

        return CommonResult.success();
    }

    @ApiOperation("充值记录")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<UserRechargeListVO>> list(UserRechargeRequest request) {
        request.setUserId(AdminUserUtil.getUserId());
        Page<UserRechargeListVO> list = userRechargeService.list(request);
        return CommonResult.success(CommonPage.restPage(list));
    }

    @ApiOperation("导出")
    @RequestMapping(value = "/down", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<String> down(UserRechargeRequest request) {
        request.setPageSize(999999);
        request.setPageNum(1);
        request.setUserId(AdminUserUtil.getUserId());
        Page<UserRechargeListVO> list = userRechargeService.list(request);
        List<UserRechargeListVO> records = list.getRecords();
        if (CollectionUtil.isNotEmpty(records)) {

            List<UserRechargeExport> userRechargeExports = records.stream().map(x -> {
                UserRechargeExport userRechargeExport = new UserRechargeExport();
                BeanUtil.copy(x, userRechargeExport);
                if (CoinType.USDT.equals(x.getCoinType())) {
                    userRechargeExport.setAmount("$" + x.getAmount());
                } else {
                    userRechargeExport.setAmount("￥" + x.getAmount());
                }
                userRechargeExport.setUsdAmount("$" + x.getUsdAmount());
                userRechargeExport.setStatus(x.getStatus().getDesc());
                PaymentType paymentType = x.getPaymentType();
                if (paymentType != null) {
                    userRechargeExport.setPaymentType(paymentType.getDesc());
                }
                SimpleUser user = x.getUser();
                if(user != null){
                    userRechargeExport.setEmail(user.getEmail());
                }
                return userRechargeExport;

            }).collect(Collectors.toList());

            String s = staticController.exports(userRechargeExports, UserRechargeExport.class);
            return CommonResult.success(s);
        }
        return CommonResult.success();
    }

    @ApiOperation("下载发票")
    @GetMapping("/downloadInvoice/{rechargeId}")
    public CommonResult<String> downloadInvoice(@PathVariable Long rechargeId, HttpServletResponse response) throws IOException {
        return userRechargeService.downloadInvoice(rechargeId, response);
    }

    // 充值
    @ApiOperation("物流查询充值")
    @PostMapping("/rechargeYear")
    public CommonResult<String> rechargeYearAmount(@RequestBody MaterialRechargeParam materialRechargeParam) {
        return userRechargeService.rechargeYear(materialRechargeParam);
    }
}

